<template>
  <div class="height100 flowstaterts whiteBgColor domainMainContent clean" ref="flowCon">
    <div class="delbtn" v-if="!this.tabNow">
      <button_item btnItemType="primary"  :btnItemLabel="$t('batchUpdateCur')" @onBtnItemClick="showBatchUser" />
      <button_item btnItemType="danger"   :btnItemLabel="$t('del')" @onBtnItemClick="onDeleteBtnClick" />
    </div>
    <el-tabs  @tab-click="handleClick" class="tabs height100 flowstatertsCon">
      <el-tab-pane :label="$t('baseInfo')" ref="flowCon" class="height100">
        <el-container class="height100">
          <el-container v-show="showmode=='LIST'" class="el-mainContent"  direction="vertical" >
            <el-form :model="searchdata.data" class="searchForm flowItem" ref="searchdata" label-position="top" label-width="180px" size="mini"  @submit.native.prevent>
              <el-row :class="showAllSearchItem?'marginB18':''">
                <el-col :span=" 4" >
                  <el-form-item  prop="application">
                    <el-select v-model="searchdata.data.application" class="el-select-w">
                      <el-option 
                        key=" "
                        :label="$t('placeholder_select')"
                        value="">
                      </el-option>
                      <el-option v-for="item in customApps.datas" 
                        :key="item.id"
                        :label="item.description?item.description:item.name"
                        :value="item.id">
                      </el-option>
                    </el-select> 
                  </el-form-item>
                </el-col>
                <el-col :span=" 4" >
                  <el-form-item  prop="_flowName">
                    <el-input :placeholder="$t('flowName')" v-model="searchdata.data._flowName" @keyup.enter.native="searchTableData"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span=" 4"  >
                  <el-form-item  prop="_stateLabel">
                    <el-input :placeholder="$t('stateLabel')" v-model="searchdata.data._stateLabel" @keyup.enter.native="searchTableData"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span=" 4"  >
                  <el-form-item  prop="_initiator">
                    <el-input :placeholder="$t('initiator')" v-model="searchdata.data._initiator" @keyup.enter.native="searchTableData"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span=" 6" class="more"  >
                      <span class="showMore" @click="showMore" v-if="!showAllSearchItem">显示更多<i class="el-icon-arrow-down"></i></span>
                      <span class="showMore" @click="foldMore" v-else>收起更多<i class="el-icon-arrow-up"></i></span>
                      <el-button type="primary" plain @click="searchData" size="small">{{$t('query')}}</el-button>
                      <el-button @click="resetForm('searchdata')" size="small">{{$t('reset')}}</el-button>
                </el-col>
              </el-row>
              <el-row v-if="showAllSearchItem">
                <el-col :span="4">
                  <el-form-item prop="_firstProcessTime"   class="marginBot10">
                    <el-date-picker :placeholder="$t('firstProcessTime')" v-model="searchdata.data._firstProcessTime" type="date" style="width: 100%"
                    value-format='yyyy-MM-dd'
                    >
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="4"  >
                  <el-form-item  prop="_lastAuditor">
                    <el-input :placeholder="$t('lastAuditor')" v-model="searchdata.data._lastAuditor" @keyup.enter.native="searchTableData"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="4"  >
                  <el-form-item  prop="_lastProcessTime">
                    <el-date-picker :placeholder="$t('lastProcessTime')" v-model="searchdata.data._lastProcessTime" type="date" style="width: 100%" value-format='yyyy-MM-dd'></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="4"  >
                  <el-form-item prop="_summary">
                    <el-input :placeholder="$t('summary')" v-model="searchdata.data._summary" @keyup.enter.native="searchTableData"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <!-- 流程监控列表 -->
            <el-table :data="tableData.datas"
              stripe
              @row-click="onRowClick"
              class="Trpointer elTags" 
              ref="multipleTable"
              @selection-change="handleSelectionChange"
              header-cell-class-name="tableHeaderbg"
              size="small"
              :row-key="handleReserve" 
              :height="tableListConHeight">
              <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
              <el-table-column prop="flowName" :label="$t('flowName')" width="180"></el-table-column>
              <el-table-column prop="stateLabel" :label="$t('stateLabel')" width="120"></el-table-column>  
              <el-table-column prop="auditorNames" :label="$t('currentApprover')" width="220">
             <template slot-scope="scope">
              <el-popover
                placement="top"
                title="当前审批人"
                trigger="hover"
              >
              <div class="drawerTags">
                <el-tag type="success" disable-transitions  v-for="(ite,index) in scope.row.auditorNames.split(',')" :key="index+ite"  class="elTag">
                 <span :title="ite">{{ite}}</span>
                </el-tag>
              </div>
              <span slot="reference">
                <div v-if="scope.row.auditorNames && (scope.row.auditorNames.split(',')).length>0"  class="columnRole">
                      <span v-for="(ite,index) in (scope.row.auditorNames).split(',')" :key="ite+index">
                     <span :title="ite">{{ite}}</span>
                      </span>
                  </div>
                </span>
                
                </el-popover>
            </template>
              </el-table-column>  
              <el-table-column prop="initiator" :label="$t('initiator')"></el-table-column>
              <el-table-column prop="firstProcessTime" sortable :label="$t('firstProcessTime')" width="180"></el-table-column>
              <el-table-column prop="lastAuditor" :label="$t('lastAuditor')" width="100"></el-table-column>
              <el-table-column prop="lastProcessTime" :label="$t('lastProcessTime')" width="180"></el-table-column>
              <el-table-column  :label="$t('summary')" width="180">
                <template slot-scope="scope">
                  <a v-html="scope.row.summary" v-if="scope.row.showTags"></a>
                  <a v-if="!scope.row.showTags">{{scope.row.summary}}</a>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination
              ref="pagination"
              @size-change="handleSizeChange"
              @current-change="searchTableData"
              :current-page.sync="searchdata.currpage"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="searchdata.pagelines"
              layout="prev, pager, next, total, sizes"
              background
              :total="tableData.rowCount?tableData.rowCount:0"
            ></el-pagination>
          </el-container>
        </el-container>
      </el-tab-pane>

      <el-tab-pane :label="$t('flowboard')" class="height100">
        <flowstaterts_panel v-if="tabNow" />
      </el-tab-pane>
    </el-tabs>
    <flowstaterts_detail @ok="ok" v-if="detailVisible" :visible.sync="detailVisible" :applicationId="detail.applicationid" :id="detail.id" :flowstatertId="detail.flowstatertId"/>
    <roleBatchUser 
      :visible.sync="roleBatchUserVisible" 
      v-if="roleBatchUserVisible" 
      :updateBatchUser="true" 
      :docIdSelection="docIdSelection"
      :showBox="false"
    />
  </div>
</template>

<script>
import flowstaterts_detail from "@/components/flowstaterts_detail.vue";

import flowstaterts_panel from "@/components/flowstaterts_panel.vue";

import roleBatchUser from "@/components/roleBatchUser.vue";
import { pxToRemScale } from '../utils'
import {delMsg} from '../utils/elementui'

export default {
  components:{
    flowstaterts_panel,
    flowstaterts_detail,
    roleBatchUser
  },
  created() {
    this.$api.getCustomAppConfig(
      { domainid: this.$route.query.domainid, data:{name: ""} },
      {
        onSucess: resp => {
          this.customApps = resp.data.data;
          // 默认选中第一个值
          if(this.customApps.datas.length > 0){
            this.searchdata.data.application = this.customApps.datas[0].id
          }
         this.searchTableData();
        }
      }
    );
  },
  mounted(){
    // this.tableListConHeight = this.$refs.flowCon.offsetHeight-40-76-44;
    let temp=pxToRemScale(68+60+46)
    this.tableListConHeight= `calc(100% - ${temp}rem)`
    console.log(this.tableListConHeight)
  },
  data() {
    return {
      searchdata: {
        domainid: this.$route.query.domainid,
        currpage: 1,
        pagelines: 10,
        
        data:{
          "application": "",
          "_flowName": "",
          "_stateLabel": "",
          "_initiator": "",
          "_firstProcessTime": "",
          "_lastProcessTime": "",
          "_lastAuditor": "",
          "_summary": "",
        }
      },
      tableData: {
        datas: [],
        rowCount: 0
      },
      showmode: "LIST",
      multipleTable:[],
      multipleSelection:[],
      docIdSelection: [],
      checked: true,
      customApps: [],
      application:"",
      tabNow:false,
      detailVisible:false,
      detail:{},
      tableListConHeight:0,
      roleBatchUserVisible:false,
      showAllSearchItem:false,
    };
  },
  methods: {
    replaceSpeChar(char){
      let text = char;
      text = text.replace(/&amp;/g, '&');
      text = text.replace(/@amp;/g, '&');
      text = text.replace(/&quot;/g, '"');
      text = text.replace(/@quot;/g, '"');
      text = text.replace(/&lt;/g, '<');
      text = text.replace(/@lt;/g, '<');
      text = text.replace(/&gt;/g, '>');
      text = text.replace(/@gt;/g, '>');
      text = text.replace(/&#146;/g, "'");
      text = text.replace(/@#146;/g, "'");
      text = text.replace(/&nbsp;/g, ' ');
      text = text.replace(/@nbsp;/g, ' ');
      text = text.replace(/&#10;/g, '\r');
      text = text.replace(/&#13;/g, '\n');
      text = text.replace(/&#9;/g, ' ');
      text = text.replace(/%23/g, '#');
      text = text.replace('\n\r', '\n');
      text = text.replace('\r\n', '\n');
      return text;
    },
    ok(){
      this.searchTableData();
    },
    handleClick(tab){
      if(tab.label==this.$t('flowboard')){
        this.tabNow=true;
      }else{
        this.tabNow=false;

      }
    },
    showBatchUser(){
      if(this.multipleSelection.length > 0){
        this.roleBatchUserVisible=true;
      }else{
          this.$message({
          showClose: true,
          message: this.$t('selectProcessRecord'),
          type: "error"
        });
      }
    },
   async onDeleteBtnClick(){
      if(this.multipleSelection.length>0){
        await delMsg(this.$t('msg_confirm_delete'), this.$t('msg_tip'),this.$t('msg_confirm'),this.$t('cancel'))
        this.$api.deleteFlowstaterts({
          applicationid: this.tableData.datas[0].applicationid,
          data: this.multipleSelection
        },{
          onSucess:resp =>{
            if(resp.data.errcode==0){

              this.$message({
                  showClose: true,
                  message: this.$t('msg_del_success'),
                  type: "success"
              });
             this.$refs.multipleTable.clearSelection(); //手动清除
              this.searchTableData()
            }else{
              this.$message({
                  showClose: true,
                  message: resp.data.errmsg,
                  type: "error"
              });
            }
          },
          onError:function(){

          }
        });
      }else{
        this.$message({
          showClose: true,
          message: this.$t('msg_select_flowdata'),
          type: "error"
        });
        return false;
      }
    },
    handleSelectionChange(val) {
      var arr = [];
      let docArr = []
      val.forEach((val) => {
        if(this.tableData.datas.length>0){
          this.tableData.datas.forEach((v) => {
            if(val.id == v.id){
              arr.push(val.id)
              docArr.push({
                applicationId: val.applicationid,
                docId: val.docId
              })
            }
          })
        }
        
      })   
      this.multipleSelection = arr;
      this.docIdSelection  = docArr
      console.log(arr, docArr)
    },
    resolvingDate(date){
      let d = new Date(date);

      let month = (d.getMonth() + 1) < 10 ? '0'+(d.getMonth() + 1) : (d.getMonth() + 1);
      let day = d.getDate()<10 ? '0'+d.getDate() : d.getDate();
      let hours = d.getHours()<10 ? '0'+d.getHours() : d.getHours();
      let min = d.getMinutes()<10 ? '0'+d.getMinutes() : d.getMinutes();
      let sec = d.getSeconds()<10 ? '0'+d.getSeconds() : d.getSeconds();

      let times=d.getFullYear() + '-' + month + '-' + day + ' ' + hours + ':' + min + ':' + sec;

      return times
    },
    searchData(){
       this.searchdata.currpage=1;
       this.searchTableData()
    },
    searchTableData(){
      if(!this.searchdata.data._firstProcessTime){
        this.searchdata.data._firstProcessTime=''
      }else{
        if(this.searchdata.data._firstProcessTime.length<=10) this.searchdata.data._firstProcessTime+=' 00:00:00'
      }
      if(!this.searchdata.data._lastProcessTime){
        this.searchdata.data._lastProcessTime=''
      }else{
        if(this.searchdata.data._lastProcessTime.length<=10) this.searchdata.data._lastProcessTime+=' 23:59:59'
      }
      this.$api.getFlowstaterts(this.searchdata, {
        onSucess: resp => {
          this.tableData = resp.data.data ? resp.data.data : {datas: [], rowCount: 0};
          // this.$set(this, 'tableData', resp.data.data)
          if(this.tableData.datas){
            this.tableData.datas.forEach(elm=>{
              elm.firstProcessTime=this.resolvingDate(elm.firstProcessTime)
              elm.lastProcessTime=this.resolvingDate(elm.lastProcessTime);
              let sum ;
              try{
                sum = JSON.parse(this.replaceSpeChar(elm.summary));
                sum = sum.summaryText.replace(/<[^>]*?>(.*?)/gi,'$1');
                elm.showTags=sum.showTags;
              }catch{
                sum = this.replaceSpeChar(elm.summary)
              }
              elm.summary=sum;
            })
            this.$nextTick(() => {
            this.$refs.multipleTable.doLayout()
          })
          }
        }
      });
    },
    
    resetForm(formName){
      this.$refs[formName].resetFields();
      this.searchTableData();
    },
    onRowClick(row) {
      this.detailVisible=true;
      this.detail=row;
    },
    handleSizeChange(size){
      this.searchdata.pagelines=size;
      this.searchTableData();
    },
    handleReserve(row){
      return row.id
    },
    showMore(){
      this.showAllSearchItem=true
    },
    foldMore(){
      this.showAllSearchItem=false
    }
  },
}
</script>